package com.swingolf.dao.hrd;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.swingolf.dao.TournamentDAO;
import com.swingolf.model.Tournament;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * The <code>HRDTemperatureDAOImpl</code> provides crud methods for accessing collecting temperatures.
 */
@Repository
public class HRDTournamentDAOImpl implements TournamentDAO {

  @Override
  public void delete(Tournament tournament) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.delete(KeyFactory.createKey("Tournament", tournament.getId()));
  }

  @Override
  public void update(Tournament tournament) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity temperatureEntity = null;
    try {
      temperatureEntity = datastore.get(KeyFactory.createKey("Tournament", tournament.getId()));
    } catch (EntityNotFoundException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    temperatureEntity.setProperty("Name", tournament.getName());
    Key key = datastore.put(temperatureEntity);
  }

  @Override
  public void save(Tournament tournament) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity temperatureEntity = new Entity("Tournament");
    temperatureEntity.setProperty("Name", tournament.getName());
    Key key = datastore.put(temperatureEntity);
    tournament.setId(key.getId());
  }

  @Override
  public List<Tournament> findAll() {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query q = new Query("Tournament");
    q.addSort("Name", Query.SortDirection.ASCENDING);
    PreparedQuery pq = datastore.prepare(q);
    List<Tournament> result = new LinkedList<Tournament>();
    Iterable<Entity> iterable = pq.asIterable();
    //for (Entity entity : iterable) {
    //  datastore.delete(entity.getKey());
    //}
    for (Entity entity : iterable) {
      result.add(new Tournament(entity.getKey().getId(), (String) entity.getProperty("Name")));
    }
    return result;

  }

  private void deleteAll() {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

  }

  @Override
  public Tournament findById(Long id) {
    Collection<Tournament> teams = findAll();
    for (Tournament team : teams) {
      if (team.getId().equals(id)) {
        return team;
      }
    }
    return null;
  }
}
